package nl.bluemango.mangotimer.delegate
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	
	import nl.bluemango.mangotimer.vo.Comment;
	import nl.bluemango.mangotimer.vo.Project;
	
	public class ProjectDelegate extends EventDispatcher
	{
		public var project:Project
		private var ph:ProjectHTML;
		public function ProjectDelegate(target:IEventDispatcher=null){
			super(target);
		}
		
		public function loadByNumber(number:int):void{
			
			project = new Project()
			project.number = number
			
			var loader:URLLoader = new URLLoader()	
			var request : URLRequest = new URLRequest("http://todo.bluemango.nl/default.aspx?url=/edit_bug.aspx&qs=id%3d"+number);  
			request.method = URLRequestMethod.POST;  
			request.useCache = false;
			
			var variables : URLVariables = new URLVariables();
			variables.__EVENTTARGET=""
			variables.__EVENTARGUMENT=""
			variables.__VIEWSTATE="/wEPDwULLTE3MjU0NzEyMTYPZBYGZg8WAh4JaW5uZXJodG1sBRZCdWdUcmFja2VyLk5FVCAtIGxvZ29uZAIBDxYCHwAFDkJ1Z1RyYWNrZXIuTkVUZAICD2QWAgICDxYCHwBlZGQ="
			variables.user="niels.wijers"
			variables.pw="flasher"
			variables.ctl01="Logon"
			
			request.data = variables;  
			
			loader.addEventListener(Event.COMPLETE, onTodoLoaded);
			loader.load(request);  
		}
		
		private function onTodoLoaded(e:Event):void{
			var html:String = e.target.data;
			ph = new ProjectHTML(html)
			project.name = ph.name;
			project.client = html.split('<select name="project"')[1].split('selected="selected"')[1].split('>')[1].split('<')[0]
			getComments(html);
			dispatchEvent(new Event(Event.COMPLETE))
		}
		
		private function getComments(html:String):void{
//			project.comments =  new ArrayCollection();
			var comments:Array = html.split('<td class=cmt')
			for (var i:int = 1; i < comments.length; i++ ){
				var c:String = comments[i]
				var comment:Comment = new Comment();
				comment.id = c.split('<a name=')[1].split('>')[0]
				comment.poster =c.split('&to=')[1].split('>')[0]
				trace(comment.body = c.split("<span class=cmt_text>")[1].split('</span>')[0])
				trace("\n --------------------- \n")
//				project.comments.addItem(comment)
			}
		}
	}
}